package com.plugin.core.util.crypt;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Slf4j
public class MySha256 {

    private static final String SHA256 = "SHA-256";

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    /**
     * 对输入字符串进行sha256散列.
     *  NoSuchAlgorithmException
     */
    public static String sha256(byte[] input,byte[] salt) {
        return digest(input, SHA256, salt, 1);
    }

    public static String sha256(byte[] input) {
        return digest(input, SHA256, null, 1);
    }

    public static String digest(byte[] msg,String algorithm,byte[] salt,int iterations) {
        MessageDigest digest = null;

        try {
            digest = MessageDigest.getInstance(SHA256);
        } catch (NoSuchAlgorithmException e) {
            log.error("exception:",e);
        }
        if (salt != null) {
            digest.update(salt);
        }
        byte[] result = digest.digest(msg);
        for (int i = 1; i < iterations; i++) {
            digest.reset();
            result = digest.digest(result);
        }
        return formatString(byte2hex(result));
    }

    private static String formatString(String sourceStr) {
        if (sourceStr == null) {
            return null;
        }
        return sourceStr.replaceAll("\\r", "").replaceAll("\\n", "");
    }


}
